#!/usr/bin/python
"""
make_syntax.py
"""

import cgi
import re
import pprint
import sys
try:
  import json
except ImportError:
  import simplejson as json


def main():
  rows = []
  doc = {'rows': rows}

  sec_name = None
  col_name = None
  row = {}
  section = {}

  for i, line in enumerate(sys.stdin):
    m = re.match('^(\w+) :(:?) \s* (.*)', line, re.VERBOSE)

    stripped = line.strip()

    if line.startswith('#'):
      # comment
      continue

    elif m:
      # Append column to row
      name = m.group(1)
      colon = m.group(2)
      value = m.group(3)
      value = value if value != '-' else ''
      # Sometimes we want < in the text.  Then just use :: instead of :.
      if colon == ':':
        value = cgi.escape(value)
      row[name] = value

    elif not stripped:
      # end of row
      if row:
        rows.append(row)
      row = {}

    elif line.startswith(' '):
      # continuation line starts with space
      row[name] += line

    else:
      raise RuntimeError('Invalid line: (%d) %r' % (i, line))

  print json.dumps(doc, indent=2)


if __name__ == '__main__':
  main()
